package cn.sfrog.project.biz.applet.controller;

import cn.hutool.http.HttpUtil;
import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.controller.BaseController;
import cn.sfrog.common.core.domain.AjaxResult;
import cn.sfrog.common.core.domain.ApiAjaxResult;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.utils.http.HttpUtils;
import cn.sfrog.common.utils.ip.AddressUtils;
import cn.sfrog.framework.web.service.SysPermissionService;
import cn.sfrog.framework.web.service.TokenService;
import cn.sfrog.project.biz.admin.utils.PhoneFormatCheckUtils;
import cn.sfrog.project.biz.admin.utils.sms.SmsResponse;
import cn.sfrog.project.biz.admin.utils.sms.SmsUtils;
import cn.sfrog.project.biz.applet.entity.AccompanyVisitorEntity;
import cn.sfrog.project.biz.applet.entity.BizUserRaffleEntity;
import cn.sfrog.project.biz.applet.entity.Test2Vo;
import cn.sfrog.project.biz.applet.entity.TestVo;
import cn.sfrog.project.biz.applet.entity.VO.AccompanyVisitorVo;
import cn.sfrog.project.biz.applet.entity.VO.AppletLoginVo;
import cn.sfrog.project.biz.applet.entity.VO.BizUserRaffleVo;
import cn.sfrog.project.biz.applet.mapper.AppletUserMapper;
import cn.sfrog.project.biz.applet.service.AppletUserService;
import cn.sfrog.project.biz.applet.utils.*;
import cn.sfrog.project.biz.web.vo.AppSendCodeVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author chen
 * @Date 2023-11-27 10:35
 * @title AppletController
 * @description
 **/
@Slf4j
@RestController
@RequestMapping("/api/applet")
@Api(value = "/api/applet", tags = "小程序相关")
public class AppletUserController extends BaseController {
    @Autowired
    AppletUserMapper appletUserMapper;
    @Autowired
    TokenService tokenService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private AppletUserService appletUserService;

    @Autowired
    private RedisCache redisCache;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.appKey}")
    private String appKey;

    @Value("${sms.appSecret}")
    private String appSecret;

    @Value("${sms.sender}")
    private String sender;

    @Value("${sms.templateId}")
    private String templateId;
    @Value("${sms.signature}")
    private String signature;

    @Value("${appletLogin.appId}")
    private String appId;

    @Value("${appletLogin.appSecret}")
    private String appSecrets;



    @ApiOperation(value = "发送注册/登录/小程序登录/修改手机号验证码", httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 500, message = "错误"),
            @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class)
    })
    @PostMapping("/sendCode")
    public ApiAjaxResult sendCode(@RequestBody @Validated AppSendCodeVO sendCodeVo) {
        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(sendCodeVo.getPhone())) {
            return ApiAjaxResult.error("手机号码有误,请重新输入");
        }
        String randomNumberCode = "";
        String key = Constants.APPLET_CACHE_PHONE_CODE_KEY + sendCodeVo.getPhone();
        // 发送验证码是否存在 如果存在
        Object cacheApplet = redisCache.getCacheObject( key );

//        默认本人所有验证码过期
        if (null == cacheApplet) {
            randomNumberCode = RandomStringUtils.randomNumeric(6);
            // 发送验证码短信
            String templateParas = "[\"".concat(randomNumberCode).concat("\"]");
            SmsResponse response = SmsUtils.sendSms(url, appKey, appSecret, sender, templateId, signature, templateParas, sendCodeVo.getPhone());

            if (response == null) {
                return ApiAjaxResult.error("验证码发送失败！");
            } else if (!Constants.PHONE_CODE_SUCCESS.equals(response.getCode())) {
                return ApiAjaxResult.error("验证码发送失败！");
            }
            redisCache.setCacheObject(key, randomNumberCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        } else {
            return ApiAjaxResult.error("您的验证码仍在有效期内，请不要频繁发送");
        }
        return ApiAjaxResult.success("验证码发送成功,您的验证码为"+randomNumberCode);
    }
    @ApiOperation(value = "小程序用户授权登录",httpMethod = "POST")
    @PostMapping("/AuthorizedLogin")
    public ApiAjaxResult AuthorizedLogin(String code,String loginCode){
        JSONObject accessTokenObject = WechatUtil.getAccessToken(appId, appSecrets);
        String accessToken = accessTokenObject.get("access_token").toString();
        JSONObject jsonObject = WechatUtil.getPhoneNumber(code,accessToken);
        if (!jsonObject.get("errmsg").toString().equals("ok")){
            return  ApiAjaxResult.error(jsonObject.get("errcode").toString(),jsonObject.get("errmsg").toString());
        }
        String phone_info = jsonObject.get("phone_info").toString();
        JSONObject json = JSONObject.parseObject(phone_info);
        String phoneNumber = json.get("phoneNumber").toString();
        return appletUserService.AuthorizedLogin(phoneNumber,loginCode);
    }
    @ApiOperation(value = "小程序登录注册登录",httpMethod = "POST")
    @PostMapping("/loginAndRegister")
    public ApiAjaxResult loginAndRegister(@RequestBody @Validated AppletLoginVo appletLoginVo){
        return appletUserService.loginAndRegister(appletLoginVo.getCode(), appletLoginVo.getPhone(),appletLoginVo.getUserId());
    }
    @ApiOperation(value = "平台抽奖",httpMethod = "GET")
    @GetMapping("/userRaffle")
    public ApiAjaxResult userRaffle(){
        return appletUserService.userRaffle();
    }
    @ApiOperation(value = "获取所有的抽奖信息",httpMethod = "GET")
    @GetMapping("/getAllBizUserRaffleInfo")
    public ApiAjaxResult AllBizUserRaffleInfo(){
        return appletUserService.bizPrizeRaffle();
    }

    @ApiOperation(value = "领奖",httpMethod = "POST")
    @PostMapping("/claimAprize")
    //@RequestBody BizUserRaffleVo bizUserRaffleVo
    public ApiAjaxResult claimAprize(@Validated @RequestBody BizUserRaffleVo bizUserRaffleVo){
        if (bizUserRaffleVo == null){
            ApiAjaxResult.error(30001,"参数错误");
        }
        BizUserRaffleEntity bizUserRaffleEntity = new BizUserRaffleEntity();
        bizUserRaffleEntity.setCreateTime(new Date());
        bizUserRaffleEntity.setRaffleId(bizUserRaffleVo.getRaffleId());
        bizUserRaffleEntity.setName(bizUserRaffleVo.getName());
        bizUserRaffleEntity.setPhone(bizUserRaffleVo.getPhone());
        return appletUserService.insertUserRaffle(bizUserRaffleEntity);
    }
    @ApiOperation(value = "获取全国的json数据",httpMethod = "POST")
    @GetMapping("/getCityJsonByChina")
    public ApiAjaxResult getCityJsonByChina() throws Exception {
//        获取ip
        HashMap<String,String> headers = new HashMap<>();
        headers.put("X-Host","mall.film-ticket.city.list");
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doGet("https://m.maizuo.com/gateway/", null, headers));
        return ApiAjaxResult.success(jsonObject);
//        Resource resource = applicationContext.getResource("classpath:city.json");
//        String jsonStr = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
//        JSONObject result = JSONObject.parseObject(jsonStr);
//        return ApiAjaxResult.success(result);
    }

    @ApiOperation(value = "陪诊陪护的就诊人信息列表",httpMethod = "GET")
    @GetMapping("/visitorAccompany")
    public ApiAjaxResult getVisitorList(Integer id){
        List<AccompanyVisitorEntity> accompanyVisitorEntities = appletUserService.visitorAccompany(String.valueOf(id));
        return ApiAjaxResult.success(accompanyVisitorEntities);
    }
    @ApiOperation(value = "插入陪诊陪护的就诊人信息",httpMethod = "POST")
    @PostMapping("/insertVisitorAccompany")
    public ApiAjaxResult insertVisitor(@RequestBody AccompanyVisitorVo accompanyVisitorVo){
//        if(accompanyVisitorVo.getUserId().toString().equals("")){
//            return ApiAjaxResult.error("user_id不能为空");
//        }
        return appletUserService.insertVisitor(accompanyVisitorVo);
    }
    @ApiOperation(value = "修改陪诊陪护的就诊人信息",httpMethod = "POST")
    @PostMapping("/changeVisitorAccompany")
    public ApiAjaxResult changeVisitorAccompany(@RequestBody AccompanyVisitorVo accompanyVisitorVo){
        accompanyVisitorVo.setUserId(null);
        return appletUserService.changeVisitorAccompany(accompanyVisitorVo);
    }
    @ApiOperation(value = "删除陪诊陪护的就诊人信息",httpMethod = "GET")
    @GetMapping("/deleteVisitorAccompany")
    public ApiAjaxResult deleteVisitorAccompany(String id){
        return appletUserService.deleteVisitorAccompany(id);
    }

    @ApiOperation(value = "获取套餐陪诊陪护的套餐",httpMethod = "GET")
    @GetMapping("/getAccompanyList")
    public ApiAjaxResult getAccompanyList(){
        return appletUserService.getAccompanyList();
    }
    @ApiOperation(value = "获取用户的定位",httpMethod = "GET")
    @GetMapping("/getUserAddress")
    public ApiAjaxResult getUserAddress(){
        return ApiAjaxResult.success();
    }
    @ApiOperation(value = "获取OpenId",httpMethod = "GET")
    @GetMapping("/getOpenId")
    public ApiAjaxResult getOpenId(String code,String phoneNumber) {
        return appletUserService.updateOpenIdByPhoneNumber(code,phoneNumber);
    }
    @ApiOperation(value = "测试",httpMethod = "POST")
    @PostMapping("/test")

    public ApiAjaxResult test(){
        List allH = appletUserMapper.getAllH();
        for (int i = 0; i < allH.size(); i++) {
            Test2Vo allD = appletUserMapper.getAllD(Integer.parseInt(allH.get(i).toString()));
            if (allD == null){
                appletUserMapper.updateAllH(Integer.parseInt(allH.get(i).toString()));
            }
        }
        return ApiAjaxResult.success();
    }

}
